<?php

namespace App\Http\Controllers\BaseSet;

use Illuminate\Http\Request;
use App\nav;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class NavController extends Controller
{
    /*
     * 加载视图
     */
    public function index(){
       $nav=nav::where('pid','0')->get();//获取第一级菜单
        $childArr=array();
        foreach ($nav as $value){
            $id=$value->id;
            $child=nav::where('pid',$id)->get();//根据pid获取子级
            $childArr[$id]=$child;
        }
        return view('BaseSet.Nav.index')->with(['nav'=>$nav,'child'=>$childArr]);
    }
    /*
     * 添加菜单栏
     */
    public function add(Request $request){
        if ($request->isMethod('post')){
            nav::create($request->all());
            return redirect()->back();
        }
        $parent=nav::where('pid',0)->get();//获取父级菜单栏
        return view('BaseSet.Nav.add')->with(['parent'=>$parent]);
    }
    /*
     * 编辑菜单栏
     */
    public function edit(Request $request){
        if ($request->isMethod('post')){
            $data=$request->all();
            $id=$data['data_id'];
            unset($data['data_id']);
            unset($data['_token']);
            nav::where('id',$id)->update($data);
            return redirect()->back();
        }
        $id=$request->all('id');
        $data=nav::where('id',$id)->get();//根据id获取菜单栏的数据
        $parent=nav::where('pid',0)->get();//获取父级菜单栏
        return view('BaseSet.Nav.edit')->with(['data'=>$data,'parent'=>$parent]);
    }
    /*
     * 删除菜单栏
     */
    /**
     * @return string
     */
    public function del(Request $request)
    {
      $id=$request->all('id');
      $pid=$request->all('pid');
      nav::destroy($id);//删除第一级菜单
      if($pid ==0)
             nav::where('pid',$pid)->delete();//删除子级
        return redirect('BaseSet/Nav');
    }
}
